// pages/activityRegistration/activityRegistration.js
const app = getApp()
const CryptoJS = require('../../utils/aes-jia.js')
var timestamp = Date.parse(new Date()) / 1000;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    payment: 0,
    id:'',
    name:"",
    tel:"",
    adult:"",
    child:"",
    money:'',
    user:'',
    money:'',
    type:'',
    isOver:true,
    prepaymentRecordId:'',
    show:false,
    walletBalance:'',
    whetherSetPayPwd:false,
    moneyChooseData: [  
      { name: 1, value: '送上礼金', checked: true},
      { name: 0, value: '现场送礼', checked: false},
    ],
  },
  //设置数据
  toggle: function (type, val) {
    this.setData({
      [type]: val
    });
  },
  payment(e) {
    var id = e.currentTarget.dataset.index
    this.setData({
      payment: id
    })
  },
  setName(e){
    this.toggle("name", e.detail.value.trim())
  },
  setTel(e) {
    this.toggle("tel", e.detail.value.trim())
  }, 
  setAdult(e) {
    this.toggle("adult", e.detail.value.trim())
  }, 
  setChild(e) {
    this.toggle("child", e.detail.value.trim())
  }, 
  setMoney(e) {
    e.detail.value = e.detail.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    e.detail.value = e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
    if (e.detail.value.indexOf(".") < 0 && e.detail.value != "") {
      e.detail.value = parseFloat(e.detail.value);
    } else if (e.detail.value.indexOf(".") == 0) {
      e.detail.value = e.detail.value.replace(/[^$#$]/g, "0.");
      e.detail.value = e.detail.value.replace(/\.{2,}/g, ".");
    }
    if (e.detail.value > 500000) {
      e.detail.value = 500000
    }
    this.toggle("money", e.detail.value)
  },

  moneyChoose(e){
    var that = this;
    var moneyChooseData = this.data.moneyChooseData;
    for (var i = 0, len = moneyChooseData.length; i < len; ++i) {
      var isCheck =  moneyChooseData[i].value == e.currentTarget.dataset.value;
      this.toggle("moneyChooseData[" + i + "].checked", isCheck)
    }
  },
  submit(){
    var that = this;
    var phonePattern = /^((\d{3}-\d{8}|\d{4}-\d{7,8})|(1[3|4|5|6|7|8|9][0-9]{9}))$/;
    if (that.data.name == '') {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return;
    } else if (that.data.tel == '') {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      })
      return;
    } else if (!phonePattern.test(that.data.tel)) {
      wx.showToast({
        title: '联系电话格式有误',
        icon: 'none'
      })
      return;
    } else if (that.data.adult == '') {
      wx.showToast({
        title: '请输入参加人数（成人）',
        icon: 'none'
      })
      return;
    } else if (that.data.adult <1) {
      wx.showToast({
        title: '参加人数（成人）至少一人',
        icon: 'none'
      })
      return;
    } else if (that.data.moneyChooseData[0].checked && (that.data.money == 0 || that.data.money.length==0)){
      wx.showToast({
        title: '请输入礼金数',
        icon: 'none'
      })
      return;
    }else{
      if (that.data.moneyChooseData[0].checked){
        that.toggle("show", true)
      }else{
      app.req({
        url: "blessmini/enrol/addEnrol",
        data: {
          blessActType: that.data.type, //1生日；2寿宴；3百日宴
          blessActId:that.data.id, //活动ID
          name: that.data.name,
          mobile: that.data.tel,
          adultCount: that.data.adult ? that.data.adult : 0,
          kidCount: that.data.adult ? that.data.kidCount : 0,
          moneyWay: 2, 
          money: that.data.money,
          payWay:"",
          prepaymentRecordId:"",
        },
        success(res){
          if(res.code==200){
            wx.navigateBack({
              delta: 1
            })
            wx.showToast({
              title: "报名成功",
              duration: 2000
            })
          }
        }
      })
      }
    }
  },
  removePopContent: function (e) {
    this.setData({
      show: false
    })
  },
  //支付
  addToActivity1(e) {
    var that = this;
    var payWay = e.currentTarget.dataset.id;
    if (payWay == 0) {
      if (that.data.walletBalance < that.data.amountRedEnvelope) {
        wx.showToast({
          title: "钱包余额不足",
          icon: 'none',
          duration: 2000
        })
        return
      } else {
        if (that.data.whetherSetPayPwd) {
          that.setData({
            showPayPwdInput: true,
            payFocus: true,
          })
        } else {
          wx.showModal({
            title: '温馨提示',
            content: '为了您的账号安全，请设置支付密码',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                wx.navigateTo({
                  url: '/pages/password/password',
                })
              }
            }
          })
        }
      }
    }
  },
  addToActivity: function (e) {
    var that = this;
    var payWay = '';
    if (e == 0) {
      payWay = 0
    } else {
      payWay = e.currentTarget.dataset.id;
    }
    if (that.data.isOver) {
      that.setData({
        isOver: false
      })
      console.log("支付方式", payWay, app.globalData.url)
      if (payWay == 1) {
        var sourceType = 5
      } else {
        var sourceType = ''
      }
      app.req({
        url: "blessmini/enrol/addEnrol?prepaymentRecordId=" + that.data.prepaymentRecordId,
        data: {
          blessActType: that.data.type, //1生日；2寿宴；3百日宴
          blessActId: that.data.id, //活动ID
          name: that.data.name,
          mobile: that.data.tel,
          adultCount: that.data.adult ? that.data.adult : 0,
          kidCount: that.data.adult ? that.data.kidCount : 0,
          moneyWay: 1,
          money: that.data.money,
          payWay: payWay,
          sourceType: sourceType,
          // prepaymentRecordId: that.data.prepaymentRecordId,
        },
        success: function (res) {
          console.log("支付", that.data.amountRedEnvelope, payWay, res)
          if (res.code == 200 && payWay == 0) {
            console.log("弹框", payWay)
            that.setData({
              show: false,
              // isOver: true
            })
            wx.navigateBack({
              delta: 1
            })
            wx.showToast({
              title: "报名成功",
              duration: 2000
            })
          } else if (res.code == 200 && payWay == 1) {
            var paydata = res.data;
            console.log("调取", paydata)
            wx.requestPayment({
              timeStamp: paydata.prepayDate.timeStamp,
              nonceStr: paydata.prepayDate.nonceStr,
              package: 'prepay_id=' + paydata.prepayDate.prepay_id,
              signType: 'MD5',
              paySign: paydata.prepayDate.paySign,
              success(res) {
                that.setData({
                  outTradeNo: paydata.outTradeNo,
                  show: false
                })
                wx.navigateBack({
                  delta: 1
                })
                wx.showToast({
                  title: "报名成功",
                  duration: 2000
                })
              },
              fail(res) {
                that.setData({
                  isOver: true
                })
                console.log("支付已取消")
                console.log(res.errMsg)
              }
            })
          } else {
            console.log('否则', payWay)
            that.setData({
              isOver: true
            })
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      });
    }
  },
  //获取钱包余额
  getWalletBalance: function () {
    let that = this
    app.req({
      url: "blessmini/user/myBalance",
      method: "post",
      data: '',
      success: function (res) {
        if (200 == res.code) {
          that.setData({
            walletBalance: res.data.balance
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  //预支付
  operationRecord() {
    let that = this
    var payPwd = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.pwdVal)
    var amount = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.money)
    console.log('预支付参数', payPwd, amount)
    app.req({
      url: "blessmini/webPayLog/operationRecord",
      method: "post",
      data: {
        payPwd: payPwd,
        amount: amount
      },
      success: function (res) {
        if (200 == res.code) {
          that.setData({
            prepaymentRecordId: res.msg,
            pwdVal: '',
          });
          console.log('预支付', that.data.prepaymentRecordId)
          that.addToActivity(0)
        } else {
          that.setData({
            pwdVal: '',
          });
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 支付密码
  /**
   * 隐藏支付密码输入层
   */
  hidePayLayer: function () {

    this.setData({
      pwdVal: '',
      showPayPwdInput: false,
      payFocus: false
    })

  },
  /**
   * 获取焦点
   */
  getFocus: function () {
    this.setData({ payFocus: true });
  },
  /**
   * 输入密码监听
   */
  inputPwd: function (e) {
    this.setData({ pwdVal: e.detail.value });
    if (this.data.pwdVal.length >= 6) {
      this.setData({
        showPayPwdInput: false,
        payFocus: false
      });
      this.operationRecord()
    }
  },
  //获取是否有密码
  getIspswd() {
    var that = this
    app.req({
      url: 'blessmini/user/whetherSetPayPwd',
      data: {
      },
      method: 'POST',
      success: function (res) {
        console.log('密码', res);
        if (res.code == 200) {
          that.setData({
            whetherSetPayPwd: res.data.whetherSetPayPwd
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.toggle('id', options.id)
    that.toggle('type', options.type)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    app.getUserInfo(function (userInfo) {
      that.setData({
        user: userInfo
      })
      that.getWalletBalance()
    })
    that.setData({
      isOver: true
    })
    that.getIspswd()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})